import { Injectable } from '@angular/core';
import * as AV from 'leancloud-storage'
import {appConfig} from 'app/config/app.config'
@Injectable()
export class LeanCloudService {
  public User
  public Object

  constructor() {
    const appId = appConfig.leancloud.appID;
    const appKey = appConfig.leancloud.appKey;
    AV.init({ appId, appKey })
    this.extend()
  }

  extend() {
    this.User = AV.User
    this.Object = AV.Object
  }

  Login(username, password) {
    return AV.User.logIn(username, password)
  }

  Query(table, page?) {
    let query = new AV.Query(table)

    if (page) {
      let { size: _size, page: _page } = page.getConfig()
      query.limit(_size);
      query.skip(_page * _size);
      page.update(query.count())
    }

    return query
  }

  send(callback) {
    let leancloud = this

    return new Promise((resolve, reject) => {
      callback({
        AV,
        leancloud
      }).then(data => {
        return resolve(data)
      }).catch(error => {
        return reject(error)
      })
    })

  }
}
